﻿using System.Collections.Generic;
using System.Linq;
using MRGSP.SurveyMaster.Core.Model;
using MRGSP.SurveyMaster.Core.Service;

namespace MRGSP.SurveyMaster.Service.Utils
{
    public class TreeBuilder : ITreeBuilder
    {
        public IEnumerable<Question> Build(IEnumerable<Question> source)
        {
            var roots = source.Where(o => source.Where(x => x.Id == o.ParentId).Count() == 0).ToArray();
            for (var index = 0; index < roots.Length; index++)
            {
                var root = roots[index];
                root = AddChildren(root, source);
                roots[index] = root;
            }

            return roots;
        }

        private static Question AddChildren(Question question, IEnumerable<Question> source)
        {
            question.Children = source.Where(o => o.ParentId == question.Id).ToArray();

            foreach (var o in question.Children)
            {
                o.Parent = question;
                AddChildren(o, source);
            }

            return question;
        }
    }
}